package com.system.service.impl;

import com.system.mapper.*;
import com.system.pojo.*;
import com.system.service.ContractService;
import com.system.utils.UUIDUtil;
import com.system.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ContractServiceImpl implements ContractService {

    @Autowired
    private PurchaseMapper purchaseMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private InvoiceMapper invoiceMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ContractGoodsMapper cgm;

    @Autowired
    private ClientMapper clientMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public ResultVo<Contract> insert(Contract contract) {
        ResultVo<Contract> resultVo = new ResultVo<Contract>();
//        System.out.println(contract);
        List<Product> products = contract.getProducts();
        List<Product> products1 = new ArrayList<>();
        boolean insert = false;
        //遍历所有购买商品，使得相同的商品归在同一类
        if(products != null && products.size() > 0){
            products1 = getPurchaseProducts(products);
        }
        insert = insertContract(contract, products1);
        //插入合同商品表
        if (insert){
            boolean b = insertContractGoods(contract.getId(), products1);
            //插入合同商品表成功
            resultVo.setInsert(true);
            resultVo.setMessage("添加合同成功");
        }else{
            throw new RuntimeException();
        }
        return resultVo;
    }

    @Override
    public ResultVo<Contract> updateById(Contract contract) {
        ResultVo<Contract> resultVo = new ResultVo<Contract>();
        int i = contractMapper.updateByPrimaryKeySelective(contract);
        if (i == 1){
            resultVo.setUpdate(true);
            resultVo.setMessage("更新成功");
        }else{
            throw new RuntimeException();
        }
        return resultVo;
    }

    @Override
    public ResultVo<Contract> selectAll() {
        return null;
    }

    @Override
    public ResultVo<Contract> selectAllDone() {
        ResultVo<Contract> resultVo = new ResultVo<Contract>();
        List<Contract> contracts = contractMapper.selectAllDone();
        if(contracts.isEmpty()){
            resultVo.setMessage("暂无已完成合同");
            return resultVo;
        }
//        List<Contract> contracts1 = new ArrayList<>();
        for (Contract contract : contracts) {
//            if (contract.getFinish() == true){
                Integer clientId = contract.getClientId();
                Integer salerId = contract.getSalerId();
                Client client = clientMapper.selectByPrimaryKey(clientId);
                SysUser sysUser = sysUserMapper.selectByPrimaryKey(salerId);
                contract.setClient(client);
                contract.setSysUser(sysUser);
//                contracts1.add(contract);
//            }
        }
//        if (contracts.isEmpty()){
//            resultVo.setMessage("暂无已完成合同");
//        }else{
            resultVo.setSelect(true);
            resultVo.setTList(contracts);
            resultVo.setMessage("查询成功");
//        }
        return resultVo;
    }

    @Override
    public ResultVo<Contract> selectAllUndone() {
        ResultVo<Contract> resultVo = new ResultVo<Contract>();
        List<Contract> contracts = contractMapper.selectAllUndone();
        if(contracts.isEmpty()){
            resultVo.setMessage("暂无未完成合同");
            return resultVo;
        }
//        List<Contract> contracts1 = new ArrayList<>();
        for (Contract contract : contracts) {
//            if (contract.getFinish() == false){
                Integer clientId = contract.getClientId();
                Integer salerId = contract.getSalerId();
                Client client = clientMapper.selectByPrimaryKey(clientId);
                SysUser sysUser = sysUserMapper.selectByPrimaryKey(salerId);
                contract.setClient(client);
                contract.setSysUser(sysUser);
//                contracts1.add(contract);
//            }
        }
//        if (contracts1.isEmpty()){
//            resultVo.setMessage("暂无未完成合同");
//        }else{
            resultVo.setSelect(true);
            resultVo.setTList(contracts);
            resultVo.setMessage("查询成功");
//        }

        return resultVo;
    }


    @Override
    public ResultVo<Contract> selectDetail(Integer contractId) {
        ResultVo<Contract> resultVo = new ResultVo<Contract>();
        Contract contract = contractMapper.selectDetail(contractId);
        resultVo.setT(contract);
        resultVo.setSelect(true);
        resultVo.setMessage("查询成功");
        return resultVo;
    }


    @Override
    public ResultVo<Contract> salerContracts(Integer uid) {
        ResultVo<Contract> resultVo = new ResultVo<Contract>();
        List<Contract> contracts = contractMapper.salerContracts(uid);
        /*List<Contract> contracts1 = new ArrayList<>();
        for (Contract contract : contracts) {
            if (contract.getSalerId() == uid){
                contracts1.add(contract);
            }
        }*/
        if(contracts.isEmpty()){
            resultVo.setMessage("该销售人员暂无签订的合同");
            return resultVo;
        }
        resultVo.setTList(contracts);
        resultVo.setSelect(true);
        resultVo.setMessage("查询成功");
        return resultVo;
    }

    @Override
    public ResultVo<Contract> addproduct(Contract contract) {
        ResultVo<Contract> resultVo = new ResultVo<Contract>();
        Contract contract1 = contractMapper.selectByPrimaryKey(contract.getId());
        //已购买的商品
        List<ContractGoods> cgs = cgm.selectByContractId(contract.getId());
        //新购买的商品
        List<Product> products = getPurchaseProducts(contract.getProducts());
        System.out.println(cgs);
        System.out.println(contract.getProducts());
        System.out.println(products);
        boolean merge = false;
        merge = mergeAndInsert(cgs,products,contract1);
        if (merge){
            resultVo.setUpdate(true);
            resultVo.setMessage("操作成功");
        }else{
            throw new RuntimeException();
        }
        return resultVo;
    }

    private boolean mergeAndInsert(List<ContractGoods> cgs, List<Product> products,Contract contract) {
        double money = 0;
        if (cgs.isEmpty() || cgs == null ){//该合同没有任何已购买商品
            for (Product product : products) {
                money += product.getPurchaseNum()*product.getPrice();
            }
            contract.addMoney(money);
            boolean b = insertContractGoods(contract.getId(), products);
            if (b){
                int i = contractMapper.updateByPrimaryKeySelective(contract);
                if (i == 1){
                    return true;
                }
            }
        }else{
            //合同已有商品，进行整合
            boolean b = mergeCgsAndProducts(cgs, products, contract);
            if (b){
                return true;
            }
        }
        return false;
    }

    private boolean mergeCgsAndProducts(List<ContractGoods> cgs, List<Product> products, Contract contract) {
        Map<String,ContractGoods> map = new HashMap<>();
        List<Product> products1 = new ArrayList<>();
        for (ContractGoods cg : cgs) {
            map.put(cg.getProductName(), cg);
        }
        for (Product product : products) {
            if (map.containsKey(product.getProductName())){
                ContractGoods contractGoods = map.get(product.getProductName());
                contractGoods.addPurchaseNum(product.getPurchaseNum());//增加购买数量
                contractGoods.addRest(product.getPurchaseNum());//增加为发货数量
                contract.addMoney(product.getPurchaseNum()*contractGoods.getPurchasePrice());//增加合同金额
            }else{//该商品未购买过
                products1.add(product);
                contract.addMoney(product.getPurchaseNum()*product.getPrice());
            }
        }
        //整合完毕，更新数据
        //更新合同总金额
        int i = contractMapper.updateByPrimaryKeySelective(contract);
        //更新合同商品表
        for (ContractGoods cg : cgs) {
            cgm.updateByPrimaryKeySelective(cg);
        }
        boolean b = insertContractGoods(contract.getId(), products1);
        if (i == 1 && b == true){
            return true;
        }
        return false;
    }

    public boolean insertContractGoods(Integer cid,List<Product> products){
        if (products != null || !products.isEmpty()){
            for (Product product : products) {
//                Product product1 = productMapper.selectByProductName(product.getProductName());
                ContractGoods cg = new ContractGoods();
                cg.setContractId(cid);
                cg.setProductId(product.getId());
                cg.setProductName(product.getProductName());
                cg.setPurchaseNum(product.getPurchaseNum());
                cg.setRest(product.getPurchaseNum());
                cg.setPurchasePrice(product.getPrice());
                int i = cgm.insertSelective(cg);
                if (i != 1){
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 插入合同信息
     * @param contract
     * @param products
     * @return
     */
    public boolean insertContract(Contract contract, List<Product> products) {
        contract.setContractNum(UUIDUtil.uniqueString(20));
        double money = 0;
        // 计算总的金额
        if (products != null){
            for (Product product : products) {
                money += product.getPrice() * product.getPurchaseNum();
            }
        }
        contract.setMoney(money);
//        contract.setSignTime(new Date());
        int i = contractMapper.insertSelective(contract);
        if (i == 1) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 对购买的商品进行去重，计数
     * @param products
     * @return
     */
    public List<Product> getPurchaseProducts(List<Product> products){
        List<Product> products1 = new ArrayList<>();
        List<Product> products2 = null;
        for (Product product : products) {
            Product product1 = productMapper.selectByProductName(product.getProductName());
            product1.setPurchaseNum(product.getPurchaseNum());
            products1.add(product1);
        }

        Map<String,Product> map = new HashMap<>();
        for (Product product : products1) {
            if (map.containsKey(product.getProductName())){
                //只修改产品的数量
                Integer num = product.getPurchaseNum();
                map.get(product.getProductName()).addPurchaseNum(num);
            }else{
                //不包括这个key
                map.put(product.getProductName(), product);
            }
        }
        products2 = new ArrayList<>(map.values());
        return products2;
    }




//
//    @Override
//    public ResultVo<Contract> updateById(Contract contract) {
//        ResultVo<Contract> resultVo = new ResultVo<Contract>();
//        //更新合同信息
//        int i = contractMapper.updateByPrimaryKeySelective(contract);
//        if(i == 1){
//            resultVo.setUpdate(true);
//            resultVo.setMessage("更新成功");
//        }else{
//            resultVo.setMessage("更新失败");
//        }
//        return resultVo;
//        //更新发货单信息
//        List<Invoice> invoices = contract.getInvoices();
//        for (Invoice invoice : invoices) {
//            String productName = invoice.getProductName();
//            Product product = productMapper.selectByProductName(productName);
//            Integer pid = product.getId();
//            invoice.setProductId(pid);
//            int i = invoiceMapper.updateByPrimaryKeySelective(invoice);
//            if (i != 1){
//                throw  new RuntimeException();
//            }
//        }
//        //添加新的产品发货单
//        List<Product> products = contract.getProducts();
//        boolean b = insertInvoices(contract.getId(), contract.getClientId(), contract.getProducts());
//        if (b){
//            resultVo.setUpdate(true);
//            resultVo.setMessage("合同更新成功");
//        }else{
//            throw  new RuntimeException();
//        }
//
//    }
//
//    @Override
//    public ResultVo<Contract> selectAll() {
//        return null;
//    }
//

//

//

//
//    *//*@Override
//    public ResultVo<Amounts> selectProductAmounts() {
//        ResultVo<Amounts> resultVo = new ResultVo<Amounts>();
//        Amounts amounts = new Amounts();
//        List<Contract> contracts = contractMapper.selectAll();
//        double money = 0;
//        for (Contract contract : contracts) {
//            money += contract.getMoney();
//        }
//        amounts.setMoney(money);
//        resultVo.setT(amounts);
//        resultVo.setSelect(true);
//        resultVo.setMessage("查询成功");
//        return resultVo;
//    }*//*
//



}
